﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sealight.Core.Domain;
using NHibernate;
using Sealight.API.Framework;
using NHibernate.Criterion;

namespace Sealight.Data
{
    public class UserRepository : NHibernateRepository<UserEntity>, IUserRepository
    {
        #region IUserRepository Members

        public bool Authenticate(string userName, string password)
        {
            IList<UserEntity> results = null;
            try
            {
                results = UnitOfWork.CurrentSession.CreateCriteria(typeof(UserEntity))
                     .Add(Expression.Eq("UserName", userName))
                     .Add(Expression.Eq("Password", password))
                     .List<UserEntity>();
            }
            catch (ADOException ex)
            {
                //log4net
                //must close session on error
                //if (UnitOfWork.CurrentSession != null && UnitOfWork.CurrentSession.IsOpen)
                //    UnitOfWork.CurrentSession.Close();
                //rethrow the exception
                throw;
            }

            return (results != null && results.Count == 1);
        }

        public bool MemberExists(string userName)
        {
           IList<UserEntity> results = null;
            try
            {
                results = UnitOfWork.CurrentSession.CreateCriteria(typeof(UserEntity))
                .Add(Expression.Eq("UserName", userName))
                    .List<UserEntity>();
            }
            catch (ADOException ex)
            {
                //log4net

                //must close session on error
                //if (UnitOfWork.CurrentSession != null && UnitOfWork.CurrentSession.IsOpen)
                //    UnitOfWork.CurrentSession.Close();
                //rethrow the exception
                throw;
            }
            return (results != null && results.Count > 0);
        }

        public UserEntity GetByUsername(string userName)
        {
            UserEntity results = null;
            try
            {
                results = UnitOfWork.CurrentSession.CreateCriteria(typeof(UserEntity))
                .Add(Expression.Eq("UserName", userName))
                    .UniqueResult<UserEntity>();
            }
            catch (ADOException ex)
            {
                //log4net

                //must close session on error
                //if (UnitOfWork.CurrentSession != null && UnitOfWork.CurrentSession.IsOpen)
                //    UnitOfWork.CurrentSession.Close();
                //rethrow the exception
                throw;
            }
            return results;
        }

        #endregion
    }
}
